package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.CheckGroupDao;
import com.itheima.dao.SetmealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.Setmeal;
import com.itheima.service.CheckGroupService;
import com.itheima.util.StaticHtml;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = CheckGroupService.class)
@Transactional
public class CheckGroupServiceImpl implements CheckGroupService {


    @Autowired
    private SetmealDao setmealDao;

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @Value("${out_put_path}")
    private String outPutPath;

    @Autowired
    private CheckGroupDao checkGroupDao;



    //添加检查组
    @Override
    public void add(CheckGroup checkGroup, Integer[] checkitemIds) {
        //添加数据
        checkGroupDao.add(checkGroup);
        //修改中间表中的数据t_checkgroup_checkitem
        //获取刚刚存入数据组的id
        Integer checkGroupId = checkGroup.getId();

        if (checkitemIds != null && checkitemIds.length > 0) {
//            for (Integer checkitemId : checkitemIds) {
//                Map<String, Integer> map = new HashMap<String, Integer>();
//                map.put("checkitemId", checkitemId);
//                map.put("checkGroupId", checkGroupId);
//                checkGroupDao.addCheckgroupAndCheckitem(map);
//            }
            this.addCheckgroupAndCheckitem(checkGroupId,checkitemIds);
        }
        //StaticHtml.generateMobileStaticHtml();
        generateMobileStaticHtml();
    }

    //检查组数据分页查询
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();

        PageHelper.startPage(currentPage,pageSize);
       Page<CheckGroup> page = checkGroupDao.findByCondition(queryString);
        return new PageResult(page.getTotal(),page.getResult());
    }

    //根据id查询检查组数据
    @Override
    public CheckGroup findById(Integer id) {
            CheckGroup checkGroup = checkGroupDao.findById(id);
            return checkGroup;

        }

        //查询检查项的id集合
    @Override
    public List<Integer> findCheckitemIds(Integer id) {
       List<Integer> list = checkGroupDao.findCheckitemIds(id);
        return list;
    }

    //修改检查组中数据（检查项，关联表）
    @Override
    public void edit(CheckGroup checkGroup, Integer[] checkitemIds) {
        //根据检查组的id,删除关联表中的数据
        Integer id = checkGroup.getId();
        checkGroupDao.delCheckGroupId(id);
        //修改检查组表中的信息
        checkGroupDao.edit(checkGroup);
        //将id添加到关联表中
        if (checkitemIds !=null && checkitemIds.length>0){
            this.addCheckgroupAndCheckitem(id,checkitemIds);
        }
      //  StaticHtml.generateMobileStaticHtml();
        generateMobileStaticHtml();
    }

    //删除检查组中的数据
    @Override
    public void delById(Integer id) {
        //查询t_setmeal_checkgroup表中检查组是否被关联了，关联了就不能被删除
        long count=checkGroupDao.findCountInSC(id);
        if (count>0){
            //t_setmeal_checkgroup表中有关联，不能删除
           throw  new RuntimeException("当前检查组被引用，不能删除");
        }else {
            //t_setmeal_checkgroup表中无关联，可以删除
            long count2=checkGroupDao.findCountInCC(id);
            if (count2>0){
                //t_checkgroup_checkitem表中有关联，先删除关联，再删除检查组
                //根据id删除中间表的关联数据
                checkGroupDao.delCheckGroupId(id);
                //根据id删除t_checkgroup表中的数据
                checkGroupDao.delById(id);
            }else {
                //t_checkgroup_checkitem表中无关联，直接删除检查组
                checkGroupDao.delById(id);
            }
        }
      //  StaticHtml.generateMobileStaticHtml();
        generateMobileStaticHtml();
    }

    //查询检查组数据
    @Override
    public List<CheckGroup> findAll() {
      return  checkGroupDao.findAll();
    }


    //    抽取出添加到中间表的方法
    public void addCheckgroupAndCheckitem(Integer checkGroupId,Integer[] checkitemIds){
        for (Integer checkitemId : checkitemIds) {
            Map<String, Integer> map = new HashMap<String, Integer>();
            map.put("checkitemId", checkitemId);
            map.put("checkGroupId", checkGroupId);
            checkGroupDao.addCheckgroupAndCheckitem(map);
        }
    }


    //生成当前方法所需的静态页面
    public void generateMobileStaticHtml(){
        //生成静态页面之前查询所有数据
        List<Setmeal> setmeals = setmealDao.getSetmeal();

        //生成套餐列表页面
        generateMobileSetmealListHtml(setmeals);

        //生成套餐详情页面
        generateMobileSetmealDetailHtml(setmeals);
    }

    //生成套餐列表页面
    public void generateMobileSetmealListHtml(List<Setmeal> setmeals){
        Map map = new HashMap();
        map.put("setmealList",setmeals);
        generateHtml("mobile_setmeal.ftl","m_setmeal.html",map);
    }
    //生成套餐详情页面
    public void generateMobileSetmealDetailHtml(List<Setmeal> setmeals){
        for (Setmeal setmeal : setmeals) {
            Map map = new HashMap();
            map.put("setmeal",setmealDao.findById(setmeal.getId()));
            generateHtml("mobile_setmeal_detail.ftl","setmeal_detail_"+setmeal.getId()+".html",map);
        }

    }

    //抽取方法，用于生成静态页面
    public void generateHtml(String templateName,String htmlPageName,Map map){
        //获取配置对象
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        //加载模板文件
        OutputStreamWriter outputStreamWriter = null;
        try {
            Template template = configuration.getTemplate(templateName);
            //创建输出流，输出静态文件
            // writer=new FileWriter(new File(outPutPath+"/"+htmlPageName));
             outputStreamWriter = new OutputStreamWriter(new FileOutputStream(outPutPath + "/" + htmlPageName),"utf-8");
            //输出文件
            template.process(map,outputStreamWriter);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
